<template>
  <!-- 设备管理 -->
  <div id="orderOutEditDiv">
    <GoBack content="商品出库" :backUrl="backUrl"></GoBack>
    <el-container>
      <div class="padding-sm" style="width: 70%; padding-top: 10px">
        <el-scrollbar style="height: 100%">

          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">领用单</div>
            </template>
            <el-descriptions-item label="出库单号">
              <vxe-input disabled v-model="orderForm.transferNo" placeholder="自动生成"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="领用科室">
              <vxe-input v-model="orderForm.receiveDept" placeholder="领用科室"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="领用时间">
              <vxe-input v-model="orderForm.receiveDate" placeholder="日期选择" type="datetime" transfer></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="发票号码">
              <vxe-input v-model="orderForm.invoiceNumber" placeholder="发票号码"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="领用人">
              <vxe-input v-model="orderForm.storagePersonnel" placeholder="领用人"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="出库人">
              <vxe-input v-model="orderForm.notifyPerson" placeholder="出库人"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="出库时间">
              <vxe-input v-model="orderForm.outDate" placeholder="日期选择" type="datetime" transfer></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="流转方式">
              <vxe-select v-model="orderForm.transferType" placeholder="请选择流转方式" style="width: 58%;">
                <vxe-option v-for="typeObj in transTypeList" :key="typeObj.transferCode" :label="typeObj.transferName" :value="typeObj.transferCode" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item></el-descriptions-item>
            <el-descriptions-item :span="3" label="备注">
              <vxe-textarea v-model="orderForm.remake"></vxe-textarea>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">出库明细
                <vxe-button @click="checkReagentDialog" type="text" class="button-blue margin-left-xs" icon="vxe-icon-square-plus">增加物品</vxe-button>
              </div>
            </template>
          </el-descriptions>
          <vxe-table ref="reagentTableRef" class="mytable-scrollbar" border="inner" align="center" :data="orderForm.reagentList" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column title="操作" align="center" fixed="left" width="50">
              <template #default="{ row }">
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteReagent(row)"></vxe-button>
              </template>
            </vxe-column>
            <vxe-column field="reaNo" title="编码" width="150"> </vxe-column>
            <vxe-column field="reaNa" title="名称" width="150"> </vxe-column>
            <vxe-column field="specModel" title="规格型号" width="150"> </vxe-column>
            <vxe-column field="batchNum" title="批号"></vxe-column>
            <vxe-column field="quantity" title="数量" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.quantity" type="text" clearable></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="unit" title="单位"></vxe-column>
            <vxe-column field="price" title="单价"></vxe-column>
            <vxe-column field="produceDate" title="生产日期"></vxe-column>
            <vxe-column field="expiryDate" title="失效日期"></vxe-column>
            <vxe-column field="uniqueCode" title="唯一编码"></vxe-column>
          </vxe-table>

        </el-scrollbar>
        <div class="footer">
          <el-form :inline="true">
            <el-row>
              <el-col :offset="1">
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="提交" :loading="sloading" @click="saveOrderInfo"></vxe-button>
                </el-form-item>
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="关闭" @click="closeMaintainOrder"></vxe-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-container>
  </div>
  <vxe-modal v-model="isStockVisiable" width="60vw" show-footer :mask="false">
    <template #title>
      <span class="text-bold">增加物品</span>
    </template>
    <template #default>
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input style="width: 130px" v-model="searchStockForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findReagentStockList" @keyup="keyupStockEnter" @search-click="findReagentStockList"></vxe-input>
          <vxe-button type="text" class="button-blue" content="查询" :loading="ploading" @click="findReagentStockList"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="stockTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="reagentStockList" :loading="ploading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column title="序号" width="80">
            <template #default="{ row, rowIndex, column }">
              <span>{{ rowIndex + 1 }}</span>
            </template>
          </vxe-column>
          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="reaNo" title="编码"></vxe-column>
          <vxe-column field="reaNa" title="商品名称"></vxe-column>
          <vxe-column field="specModel" title="规格型号"></vxe-column>
          <vxe-column field="batchNum" title="批号"></vxe-column>
          <vxe-column field="quantity" title="数量"></vxe-column>
          <vxe-column field="unit" title="单位"></vxe-column>
          <vxe-column field="price" title="单价"></vxe-column>
          <vxe-column field="produceDate" title="生产日期"></vxe-column>
          <vxe-column field="expiryDate" title="失效日期"></vxe-column>
          <vxe-column field="uniqueCode" title="唯一编码"></vxe-column>
        </vxe-table>
      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelStockEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="confirmStockEvent">确定</vxe-button>
    </template>
  </vxe-modal>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, notifyMessage, notifyType } from '@/utils/common';
import GoBack from '@/components/GoBackNew.vue'; //返回组件
let { proxy }: any = getCurrentInstance();

let backUrl = ref(null);
let transTypeList: any = reactive([]);
let sloading = ref(false);

let orderForm: any = reactive({
  id: null,
  transferNo: '',
  transferType: '',
  orderStatus: '',
  supplierCode: '',
  supplierName: '',
  tarStoreNa: '',
  tarStoreCode: '',
  invoiceNumber: '',
  invoiceDate: '',
  documentDate: '',
  purOrderNumber: '',
  outOrderNumber: '',
  businessType: '',
  storagePersonnel: '',
  storageMark: '',
  notifyPerson: '',
  notifyDate: '',
  remake: '',
  receiveDept: '',
  receiveDate: '',
  outDate: '',
  seq: null,
  reagentList: []
});

onMounted(() => {
  if (!IsEmpty(proxy.$route.query.url)) {
    backUrl.value = proxy.$route.query.url.toString();
  }
  if (!IsEmpty(proxy.$route.query.transferType)) {
    orderForm.transferType = proxy.$route.query.transferType.toString();
  }
  findInvTransTypeList();
});
//获取流转集合
async function findInvTransTypeList() {
  const url = '/inv/transfer/type/findInvTransferTypeList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, { params: { businessType: '02' } })
    .then((res: any) => {
      if (res.status.code === 1) {
        transTypeList.push(...res.data);
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}
let isStockVisiable = ref(false);
let reagentStockList: any = reactive([]); //弹框表格数据
let ploading = ref(false); //弹框表格数据加载状态
let searchStockForm = reactive({
  searchValue: ''
});
function checkReagentDialog() {
  findReagentStockList();
  isStockVisiable.value = true;
}

function keyupStockEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReagentStockList();
  }
}
function findReagentStockList() {
  ploading.value = true;
  reagentStockList.length = 0; //放入数据前清空数据
  const url = '/inv/invReagentStock/findReagentStockList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchStockForm.searchValue,
        query0Flag: true
      }
    })
    .then((res: any) => {
      reagentStockList.push(...res.data);

      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

async function confirmStockEvent() {
  const selectRows = (proxy.$refs.stockTableRef as any).getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择库存', VxeNotifyType.error);
  } else {
    for (const sltEmploy of selectRows) {
      let cnt = orderForm.reagentList.findIndex((a: any) => a.stockId == sltEmploy.id);
      if (cnt > -1) {
        continue;
      }
      let outStock = {
        orderInfoId: orderForm.id,
        stockId: sltEmploy.id,
        reaNo: sltEmploy.reaNo,
        reaNa: sltEmploy.reaNa,
        specModel: sltEmploy.specModel,
        batchNum: sltEmploy.batchNum,
        quantity: sltEmploy.quantity,
        unit: sltEmploy.unit,
        price: sltEmploy.price,
        produceDate: sltEmploy.produceDate,
        expiryDate: sltEmploy.expiryDate,
        uniqueCode: sltEmploy.uniqueCode,
        seq: 1
      };
      orderForm.reagentList.push(outStock);
    }
    isStockVisiable.value = false;
  }
}

function deleteReagent(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const $table = proxy.$refs.reagentTableRef as any;

      if ($table) {
        let cnt = orderForm.reagentList.findIndex((a: any) => a.stockId == row.stockId);
        if (cnt > -1) {
          await $table.remove(row);
          orderForm.reagentList.splice(cnt, 1);
          VxeMessage('删除成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function saveOrderInfo() {
  sloading.value = true;
  if (orderForm.id === null) {
    const url = '/inv/orderInfo/addOrderInfo';
    const supplier = {
      transferNo: orderForm.transferNo,
      transferType: orderForm.transferType,
      orderStatus: '5',
      supplierCode: orderForm.supplierCode,
      supplierName: orderForm.supplierCode,
      tarStoreNa: orderForm.tarStoreNa,
      tarStoreCode: orderForm.tarStoreCode,
      invoiceNumber: orderForm.invoiceNumber,
      invoiceDate: orderForm.invoiceDate,
      documentDate: orderForm.documentDate,
      purOrderNumber: orderForm.purOrderNumber,
      outOrderNumber: orderForm.outOrderNumber,
      businessType: orderForm.businessType,
      storagePersonnel: orderForm.storagePersonnel,
      storageMark: orderForm.storageMark,
      notifyPerson: orderForm.notifyPerson,
      notifyDate: orderForm.notifyDate,
      remake: orderForm.remake,
      receiveDept: orderForm.receiveDept,
      receiveDate: orderForm.receiveDate,
      outDate: orderForm.outDate,
      seq: orderForm.seq,
      reagentList: orderForm.reagentList
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('新增成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { orderId: res.data.id } });
        } else {
          VxeMessage('新增失败', VxeNotifyType.error);
        }
        sloading.value = false;
        //findQiIndexSqlOne();
      })
      .catch((err: any) => {
        sloading.value = false;
        console.log(err);
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/api/eq/eqMaintainOrder/updateMaintainOrder';

    const supplier = {
      id: orderform.id,
      equiptId: orderform.equiptId,
      equiptCode: orderform.equiptCode,
      equiptName: orderform.equiptName,
      specification: orderform.specification,
      maintainNo: orderform.maintainNo,
      maintainType: orderform.maintainType,
      maintainStatus: orderform.maintainStatus,
      startDate: orderform.startDate,
      endDate: orderform.endDate,
      workHours: orderform.workHours,
      maintainFee: orderform.maintainFee,
      remark: orderform.remark,
      maintainPersonList: orderform.maintainPersonList,
      maintainDetailList: orderform.maintainDetailList
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('修改成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { orderId: orderform.id, planId: planId.value, xgjlUrl: xgjlUrl.value, pageSize: pageSize.value, pageIndex: pageIndex.value } });
        } else {
          VxeMessage('修改失败', VxeNotifyType.error);
        }
        sloading.value = false;
      })
      .catch((err: any) => {
        sloading.value = false;
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

function cancelStockEvent() {
  isStockVisiable.value = false;
}
</script>
<style lang="scss" scoped>
#orderOutEditDiv {
  .el-descriptions {
    margin-top: 10px;
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    box-shadow: 8px 8px 15px #909399;
    background-color: $bg-gray;
    z-index: 9999;
    .el-form {
      transform: translateX(5%);
    }
    .el-form-item {
      margin-bottom: 0;
      margin-right: 12px;
    }
  }
}
</style>